<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      style="margin-top: 20px;"
    >
      <el-form-item label="菜单名" prop="sysReName">
        <el-input
          v-model="queryParams.sysReName"
          placeholder="请输入菜单名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单路径" prop="sysReUrl">
        <el-input
          v-model="queryParams.sysReUrl"
          placeholder="请输入菜单路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限标识" prop="sysRePer">
        <el-input
          v-model="queryParams.sysRePer"
          placeholder="请输入权限标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

     
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


     <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="testList"
      row-key="sysReId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="sysReName" label="菜单名称" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column prop="sysReIcon" label="图标" align="center" width="100">
        <template slot-scope="scope" #default="scope">
          <svg-icon :icon-class="scope.row.sysReIcon" />
        </template>
      </el-table-column>
      <el-table-column prop="sysReSort" label="排序" width="60"></el-table-column>
      <el-table-column prop="sysRePer" label="权限标识" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="sysReUrl" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="sysReStatu" label="状态" width="80" :show-overflow-tooltip="true">
      
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="sysReCretime">
        <template slot-scope="scope"   #default="scope">
          <span>{{ parseTime(scope.row.sysReCretime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" #default="scope">
          <el-button 
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table> 


    <el-dialog :title="title" v-model="open" width="680px" :append-to-body="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单" prop="parentId">
              <el-tree :data="testLists" 
              :props="defaultProps"
               @node-click="handleNodeClick"></el-tree>

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.sysReType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12" v-if="form.menuType != 'M'">
            <el-form-item prop="perms" label="权限字符">
              <el-input v-model="form.sysRePer" placeholder="请输入权限标识" maxlength="100" />
            
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.sysReType != 'F'">
            <el-form-item prop="path" label="路由地址">
             
              <el-input v-model="form.sysReUrl" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sysReSort">
              <el-input-number v-model="form.sysReSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态" prop="sysStatu">
              <el-switch
                v-model="form.sysStatu"
                :active-value="1" :inactive-value="0"
              
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
   
  </div>
</template>


<script>
import { listTest, getTest, delTest, addTest, updateTest } from "../../api/sys/resoure";

export default {
  name: "Test",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      isExpandAll: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      testList: [],
      testLists:[
        
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultProps: {
        children: 'children',
          label: 'sysReName'
        },
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sysReName: null,
        sysReType: null,
        sysReUrl: null,
        sysRePer: null,
        sysReParanterid: null,
        sysReSort: null,
        sysReStatu: null,
        sysReCretime: null,
        sysReUpdatetime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
       // 菜单表格树数据
       menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
     tiletree:"",
     refreshTable: true,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listTest(this.queryParams).then(response => {
        this.testList = response.rows;
      
        this.total = response.total;
        this.loading = false;
      });
    },
    parseTime(time, pattern) 
      {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
},
    trList(item){
   console.log(item);
      
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sysReId: null,
        sysReName: null,
        sysReType: null,
        sysReUrl: null,
        sysRePer: null,
        sysReParanterid: null,
        sysReSort: null,
        sysReStatu: null,
        sysReCretime: null,
        sysReUpdatetime: null
      };
      this.resetForm("form");
    },
    resetForm(refName) {
      console.log(this.$refs[refName]);
      if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sysReId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sysReId = row.sysReId || this.ids
      this.title = "修改";
     
     
      this.form=row
      this.testLists.children = row
      this.testLists.sysReName = row.sysReName
      this.open = true;
  
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sysReId != null) {
            updateTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      this.$confirm('是否确认删除【菜单名称】为"' + row.sysReName + '"的数据项？').then(function() {
        return delTest(row.sysReId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/test/export', {
        ...this.queryParams
      }, `test_${new Date().getTime()}.xlsx`)
    },
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    parseTime(time, pattern) 
      {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
},
normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
  },
  getTreeselect() {
      listMenu().then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },

}
}
</script>

<style>

  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>